<template>
    <div class="box box8">
        <!-- <ImmersiveNavbar title="眨眨眼" /> -->
        <div @click="back" class="image-1"></div>
        <div class="box8_text">眨眨眼</div>
        <div class="zhezhao">
            <div class="box8_mask"></div>
            <div v-if="block1" class="son"></div>
        </div>

        <img :src="overlayImg" alt="" class="img_png" @click="goToBox9">
        <video ref="video" class="camera-feed" autoplay playsinline></video>
        <!-- 黑色遮罩 -->

    </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import overlayImg from '@/assets/img/09.png'


// import ImmersiveNavbar from '@/components/ImmersiveNavbar.vue'
const router = useRouter()
// const block1 = ref(false)
function goToBox9() { router.replace('/box9') }
function back() {
    router.push('/box7')
}
onMounted(() => {
})

// 引入 uni

</script>

<script>
/* global plus */
export default {
    name: 'BoxEight',
    data() {
        return {
            cameraStream: null,
            plusCamera: null,
            startX: 0,
            startY: 0,
            block1: true
        }
    },
    created() {
        setTimeout(() => {
            this.block1 = false
        }, 1800);
        setTimeout(() => {
            this.$router.replace('/box9')
        }, 5000);
    },

    mounted() {
        document.addEventListener('plusready', this.handleBackButton);
        // 设置沉浸式状态栏：深色文字、浅色背景
        this.setStatusBarDark()
        document.addEventListener('plusready', this.handlePlusReady)
        // 兼容H5和APP
        if (window.plus && plus.camera) {
            // APP环境 - 使用plus.camera的预览功能
            this.startPlusCamera();
        } else if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            // H5环境
            this.startH5Camera();
        } else {
            // 可能是 plus 延迟加载，等待一下再试
            setTimeout(() => {
                if (window.plus && plus.camera) {
                    this.startPlusCamera();
                } else {
                    alert('当前环境不支持摄像头');
                }
            }, 1000);
        }
    },
    methods: {
        handlePlusReady() {
            this.setStatusBarDark()
        },
        setStatusBarDark() {
            if (typeof plus !== 'undefined' && plus.navigator) {
                try {
                    plus.navigator.setStatusBarStyle('dark')
                    plus.navigator.setStatusBarBackground('#ffffff')
                } catch (e) { console.warn('Box8 setStatusBarDark failed', e) }
            }
        },
        restoreStatusBarDefault() {
            if (typeof plus !== 'undefined' && plus.navigator) {
                try {
                    plus.navigator.setStatusBarStyle('light')
                    plus.navigator.setStatusBarBackground('#00000000')
                } catch (e) { console.warn('Box8 restoreStatusBarDefault failed', e) }
            }
        },
        handleBackButton() {
            if (typeof plus !== 'undefined' && plus.key) {
                this.backButtonHandler = (e) => {
                    e.preventDefault && e.preventDefault();
                    e.stopPropagation && e.stopPropagation();
                    
                    if (this.$route.path !== '/box1') {
                        this.$router.push('/box7');
                    } else {
                        if (confirm('再按一次退出应用')) {
                            plus.runtime.quit();
                        }
                    }
                    return false;
                };
                plus.key.addEventListener('backbutton', this.backButtonHandler);
            }
        },
        // H5环境摄像头
        startH5Camera() {
            navigator.mediaDevices.getUserMedia({
                video: {
                    facingMode: 'user', // 前置摄像头
                    width: { ideal: 640 },
                    height: { ideal: 480 }
                }
            })
                .then(stream => {
                    this.$refs.video.srcObject = stream;
                    this.cameraStream = stream;
                    console.log('H5摄像头启动成功');
                })
                .catch(err => {
                    console.error('H5摄像头启动失败:', err);
                    alert('无法访问摄像头: ' + err.message);
                });
        },

        handleTouchStart(e) {
            this.startX = e.touches[0].clientX
            this.startY = e.touches[0].clientY
        },
        handleTouchEnd(e) {
            const endX = e.changedTouches[0].clientX
            const endY = e.changedTouches[0].clientY
            const deltaX = endX - this.startX
            const deltaY = endY - this.startY
            if (Math.abs(deltaX) > 50 && Math.abs(deltaY) < 30) {
                if (deltaX > 0) {
                    this.goPrev()
                } else {
                    this.goNext()
                }
            }
        },
        goPrev() {
            this.$router.push('/box7')
        },
        goNext() {
            this.$router.push('/box9')
        },
        startPlusCamera() {
            // #ifdef APP-PLUS
            try {
                console.log('开始初始化APP摄像头...');
                console.log('plus对象:', window.plus);
                console.log('plus.camera对象:', plus.camera);

                // 检查plus.camera是否可用
                if (!plus.camera) {
                    throw new Error('plus.camera 不可用');
                }

                // 尝试使用plus.camera的预览功能
                if (plus.camera.getCamera) {
                    try {
                        this.plusCamera = plus.camera.getCamera();
                        console.log('获取摄像头实例成功:', this.plusCamera);

                        // 方法1: 尝试使用startPreview并绑定到video元素
                        if (this.plusCamera.startPreview) {
                            this.startPreviewToVideo();
                        } else {
                            throw new Error('startPreview方法不存在');
                        }

                    } catch (e) {
                        console.log('plus.camera.getCamera失败:', e.message);
                        // 如果plus.camera失败，尝试使用H5方式
                        this.startH5Camera();
                    }
                } else {
                    throw new Error('plus.camera.getCamera方法不存在');
                }

            } catch (e) {
                console.error('APP摄像头异常:', e);
                console.error('异常堆栈:', e.stack);
                // 如果APP方式失败，尝试H5方式
                console.log('尝试使用H5摄像头...');
                this.startH5Camera();
            }
            // #endif
        },

        startPreviewToVideo() {
            try {
                // 获取video元素
                const videoElement = this.$refs.video;
                if (!videoElement) {
                    throw new Error('video元素不存在');
                }

                console.log('开始预览到video元素...');

                // 使用plus.camera的预览功能
                this.plusCamera.startPreview(
                    (path) => {
                        console.log('摄像头预览开始: ' + path);
                        // 这里path可能是预览的URL，尝试设置到video
                        if (path && typeof path === 'string') {
                            videoElement.src = path;
                        }
                        alert('摄像头预览成功启动');
                    },
                    (err) => {
                        console.error('摄像头预览失败:', err);
                        alert('摄像头预览失败: ' + JSON.stringify(err));
                        // 如果预览失败，尝试H5方式
                        this.startH5Camera();
                    },
                    {
                        index: 1, // 前置摄像头
                        format: 'jpg',
                        quality: 100,
                        video: {
                            width: 640,
                            height: 480,
                            bitrate: 1000000,
                            fps: 30
                        }
                    }
                );

            } catch (e) {
                console.error('预览到video失败:', e);
                // 如果失败，尝试H5方式
                this.startH5Camera();
            }
        }
    },
    beforeUnmount() {
        document.removeEventListener('plusready', this.handleBackButton);
        document.removeEventListener('plusready', this.handlePlusReady);
        this.restoreStatusBarDefault()

        // 移除返回键监听器
        if (typeof plus !== 'undefined' && plus.key && this.backButtonHandler) {
            plus.key.removeEventListener('backbutton', this.backButtonHandler);
        }

        // 关闭摄像头
        if (this.cameraStream) {
            this.cameraStream.getTracks().forEach(track => track.stop());
        }
        // APP环境下关闭plus.camera预览
        if (this.plusCamera && this.plusCamera.stopPreview) {
            try {
                this.plusCamera.stopPreview();
            } catch (e) {
                console.log('关闭摄像头异常: ' + e.message);
            }
        }
    }
}
</script>

<style scoped>
.camera-feed::-webkit-media-controls {
    display: none !important;
}

.camera-feed::-webkit-media-controls-play-button,
.camera-feed::-webkit-media-controls-start-playback-button {
    display: none !important;
    -webkit-appearance: none;
}

/*  */
.zhezhao {
    position: relative;
    position: absolute;
    width: 248px;
    height: 248px;
    border-radius: 50%;
    /* background-color: pink; */
    left: 63px;
    top: 177px;
    z-index: 99;
    overflow: hidden;

}

.son {
    top: 0;
    left: 0;
    position: absolute;
    width: 248px;
    height: 248px;
    background-color: #000;
}

.box8_mask {
    height: 70px;
    overflow: hidden;
    background: rgba(0, 0, 0, 0.2);
    width: 100%;
    z-index: 1000;


}


.box {
    position: relative;
    width: 375px;
    height: 100vh;
    position: absolute;
    overflow: auto;
    background: #fff;
    padding-top: 44px;
}

.image-1 {
    position: absolute;
    width: 30px;
    height: 30px;
    /* background-color: rgb(50, 44, 45); */

    opacity: 0.1;
    top: 40px;
    left: 15px;
    z-index: 99;
}

.image {
    width: 375px;
}

.camera-feed {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transform: scaleX(-1);
}

.img_png {
    width: 375px;
    position: absolute;
    top: 0;
    left: 0;
}

.box8_text {
    position: absolute;
    top: 201px;
    left: 50%;
    transform: translateX(-50%);
    color: #fff;
    font-size: 24px;
    z-index: 10;
}

.camera-feed {
    position: absolute;
    left: 63px;
    top: 177px;
    width: 248px;
    height: 248px;
    border-radius: 50%;
    background: #000;
}
</style>